package com.ws.shop.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 工具类 - Spring
 */

public class SpringUtil implements ServletContextListener {

	private static WebApplicationContext rootApplicationContext;
	private static WebApplicationContext frontApplicationContext;
	private static WebApplicationContext adminApplicationContext;
	private static ServletContext servletContext;

	public static WebApplicationContext getFrontApplicationContext() {
		return frontApplicationContext;
	}

	public static void setFrontApplicationContext(
			WebApplicationContext frontApplicationContext) {
		SpringUtil.frontApplicationContext = frontApplicationContext;
	}

	public static WebApplicationContext getRootApplicationContext() {
		return rootApplicationContext;
	}

	public static WebApplicationContext getAdminApplicationContext() {
		return adminApplicationContext;
	}

	public static void setAdminApplicationContext(
			WebApplicationContext adminApplicationContext) {
		SpringUtil.adminApplicationContext = adminApplicationContext;
	}

	/**
	 * 根据Bean名称获取实例
	 * 
	 * @param name
	 *            Bean注册名称
	 * 
	 * @return bean实例
	 * 
	 * @throws BeansException
	 */
	public static Object getBean(String name) throws BeansException {
		return rootApplicationContext.getBean(name);
	}
	
	public static <T> T getBean(Class<T> T){
		return rootApplicationContext.getBean(T);
	}
	
	public static Object getBeanFromFrontApplicationContext(String name){
		return frontApplicationContext.getBean(name);
	}
	
	public static <T> T getBeanFromFrontApplicationContext(Class<T> T){
		return frontApplicationContext.getBean(T);
	}
	
	public static Object getBeanFromAdminApplicationContext(String name){
		return adminApplicationContext.getBean(name);
	}
	
	public static <T> T getBeanFromAdminApplicationContext(Class<T> T){
		return adminApplicationContext.getBean(T);
	}

	public static ServletContext getServletContext(){
		return servletContext;
	}
	
	public static String getRealPath(String path){
		return servletContext.getRealPath(path);
	}

	public void contextDestroyed(ServletContextEvent arg0) {}

	public void contextInitialized(ServletContextEvent event) {
		rootApplicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
		servletContext = SpringUtil.rootApplicationContext.getServletContext();
	}
}